package es.qplayas;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import es.qplayas.core.Playa;
import es.qplayas.core.Posicion;

public class BeachHome extends ListActivity {
	
	private List<Playa> playas;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activateLocation();
		
		ConectivityManager cm = new ConectivityManager();
		JSONObject json = cm.getData("http://192.168.0.150/test.html");
		BeachParser parser = new BeachParser();
		playas = parser.parse(json);

		setContentView(R.layout.listplaceholder);
		
		final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		Playa playa = null;
        		for(Playa pl:playas){
        			if(pl.getId() == position){
        				playa = pl;
        				break;
        			}
        		}
        		change(playa);
        	}
		});
		
	}
	
	private void updateList(Location geopos){
		ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
		try{
			for(Playa playa:playas){
				playa.setDistancia(getDistance(playa.getPosicion(),geopos));
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("id",  String.valueOf(playa.getId()));
				map.put("name", playa.getNombre());
				map.put("city", "Localidad: " +  playa.getLocalidad() + ", distancia: " + playa.getDistancia()  + " Km");
				mylist.add(map);
			}
		}catch(Exception e)        {
			e.printStackTrace();
		}
		ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
				new String[] { "name", "city" },
				new int[] { R.id.item_title, R.id.item_subtitle });

		setListAdapter(adapter);
	}
	
	private float getDistance(Posicion pos, Location geopos){
		float[] results = new float[3];
		Location.distanceBetween(geopos.getLatitude(), geopos.getLongitude(), pos.getLatitud(), pos.getLongitud(), results);
		return results[0]/1000;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.beach_menu, menu);
	    return true;
	}
	
	private void change(Playa playa){
		Intent intent = new Intent(this, Details.class);
		intent.putExtra("playa",playa);
    	startActivity(intent);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.beach_menu:
	    	Intent intent = new Intent(this, FiltersForm.class);
	    	startActivity(intent);
	    	return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	private void activateLocation(){
		LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
            	updateList(location);
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {}

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {}
          };

        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5, 0, locationListener);
	}
}